import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

//导入持久化依赖包
import VuexPersistence from "vuex-persist";
//实例化持久化插件对象
const vuexLocal = new VuexPersistence({
  storage: window.localStorage, //存储介质,
  key: "vuex", //存储到本地存储
});

export default new Vuex.Store({
  state: {
    user: {},
    token: "",
    goodslist: [],
  },
  mutations: {
    login(state, data) {
      state.user = data;
      state.token = data.password;
    },
    addgoods(state, data) {
      let index = state.goodslist.findIndex((item) => {
        return item._id == data._id;
      });
      if(index > -1){
        state.goodslist[index].num++
      }else{
        state.goodslist.push(data);
      }
    },
    delgoods(state, id) {
      let a = state.goodslist.filter((item) => {
        return item._id != id;
      });
      state.goodslist = a;
    },
  },
  actions: {},
  plugins: [vuexLocal.plugin],
});
